﻿using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Mysoft.Common.Configuration;
using Mysoft.Common.Extensions;
using Mysoft.Common.Response;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mysoft.AppStartup.Container
{
    /// <summary>
    /// jwt注册
    /// </summary>
    public static class AddAuthentication
    {
        public static void Register(IServiceCollection services) {
            //添加token身份认证到容器
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
                {
                    SaveSigninToken = true,//保存token
                    ValidateIssuerSigningKey = true,//是否调用对签名securityToken的SecurityKey进行验证
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(AppSetting.JWTToken.Secret)),//签名秘钥
                    ValidateIssuer = true,//是否验证颁发者
                    ValidIssuer = AppSetting.JWTToken.Issuer,//颁发者
                    ValidateAudience = true,//是否验证接收者
                    ValidAudience = AppSetting.JWTToken.Audience,//接收者
                    ValidateLifetime = true,//是否验证失效时间
                    ClockSkew = TimeSpan.FromSeconds(AppSetting.JWTToken.ClockSkew * 60)//过期时间偏移量
                };
                x.Events = new JwtBearerEvents()
                {
                    OnChallenge = context =>
                    {
                        context.HandleResponse();
                        context.Response.Clear();
                        context.Response.ContentType = "application/json";
                        context.Response.StatusCode = 401;
                        context.Response.WriteAsync(new ErrorResponse { message = "没有访问权限!", success = false, code = 401 }.Serialize());
                        return Task.CompletedTask;
                    }
                };
            });
        }
    }
}
